// 登录状态管理
import { defineStore } from 'pinia';
import { getUserProfile } from '../api/users';

interface UserState {
  token: string | null;
  userInfo: Record<string, any> | null;
}

export const useAuthStore = defineStore('auth', {
  state: (): UserState => ({
    token: localStorage.getItem('token'),
    userInfo: null
  }),
  actions: {
    async loginSuccess(token: string) {
      this.token = token;
      localStorage.setItem('token', token);
      await this.fetchUserInfo();
    },
    async fetchUserInfo() {
      try {
        if (!this.token) throw new Error('未找到有效Token');
        
        const { data } = await getUserProfile();
        // 移除头像字段处理
        this.userInfo = { ...data.data };
        
        localStorage.setItem('user', JSON.stringify(this.userInfo));
      } catch (error) {
        console.error('用户信息请求失败:', error);
        this.logout();
        throw error;
      }
    },
    logout() {
      this.token = null;
      this.userInfo = null;
      localStorage.removeItem('token');
      localStorage.removeItem('user');
    }
  }
});
